package conversion.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import conversion.bean.User;
import conversion.utils.JwtUtils;
import conversion.vo.SecurityUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;


import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 定义一次性请求过滤器
 */
@Component
@Slf4j
public class JwtCheckFilter extends OncePerRequestFilter {
    @Resource
    private ObjectMapper objectMapper;
    @Resource
    private JwtUtils jwtUtils;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
//         判断是否是静态资源请求
//        if (isIgnoreResourceRequest(request)) {
//            filterChain.doFilter(request, response);
//            return;
//        }
        //获取请求uri
        String requestURI = request.getRequestURI();
        log.info(requestURI);
//        response.setHeader("requestURI",requestURI);
        HttpSession session = request.getSession();
        // 检查是否包含 token
            Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("token")) {
                    String token = cookie.getValue();
//                    if ("".equals(token)){
//                        return;
//                    }
                    // 验证 token 的合法性
                    boolean isValidToken = jwtUtils.verifyToken(token);
                    if (isValidToken) {
                        // 从 token 中获取用户信息
                        String userInfo = jwtUtils.getUserInfo(token);
                        User user = objectMapper.readValue(userInfo, User.class);
                        List<String> userAuth = jwtUtils.getUserAuth(token);
                        SecurityUser securityUser = new SecurityUser(user);
                        List<SimpleGrantedAuthority> authList = userAuth.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
                        securityUser.setAuthorityList(authList);
                        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToke = new UsernamePasswordAuthenticationToken(securityUser
                                , null, authList);
                        //通过安全上下文设置认证信息
                        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToke);

                        if (user != null) {
                            // 将用户信息放入 session
                            session.setAttribute("user", user);
                            //如果你已登录还行访问登录页面，则进行拦截
                            if("/login".equals(requestURI)){
                                log.info("重定向index");
                                response.sendRedirect("/index");
                            }
                            // 放行
                            log.info("放行");
                            //继续访问相应的rul等
                            filterChain.doFilter(request, response);
                            return;

                        }
                    }
                    else {
                        filterChain.doFilter(request, response);
                        return;
                    }
                }
            }
        }
        filterChain.doFilter(request, response);


    }
    private boolean isIgnoreResourceRequest(HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        String[] staticResourcePaths = { "/css/", "/js/", "/images/", "/avatars/" ,"/account/sendEmail","/account/register"};

        for (String path : staticResourcePaths) {
            if (requestURI.startsWith(path)) {
                return true;
            }
        }

        return false;
    }
}

